package dcp.bss.modules.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import dcp.bss.common.util.DateUtils;
import dcp.bss.common.util.IPUtils;
import dcp.bss.common.util.Constant;
import dcp.bss.common.util.PageUtils;
import dcp.bss.web.util.Query;
import dcp.bss.modules.sys.entity.SysUserEntity;
import dcp.bss.modules.sys.dao.SysUserDao;
import dcp.bss.modules.sys.service.SysLogService;
import dcp.bss.modules.sys.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 系统用户
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年9月18日 上午9:46:09
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {

	@Autowired
	private SysLogService sysLogService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String)params.get("username");
		Page<SysUserEntity> page = this.selectPage(
			new Query<SysUserEntity>(params).getPage(),
			new EntityWrapper<SysUserEntity>()
				.like(StringUtils.isNotBlank(username),"username", username)
		);

		return new PageUtils(page);
	}

	@Override
	public List<SysUserEntity> queryByid(Long id) {
		return this.selectList(
				new EntityWrapper<SysUserEntity>()
						.eq(id != null,"ip_pk", id)
		);
	}


	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String username) {
		return baseMapper.queryByUserName(username);
	}

	@Override
	@Async
	public void saveLoginTime(HttpServletRequest request,Long userId, String username) {

		SysUserEntity user2 = new SysUserEntity();
		user2.setUserId(userId);
		//设置最后登录时间
		user2.setLoginTime(DateUtils.getCurrentTime());
		String newip=IPUtils.getIpAddr(request);
		if(newip!=null && newip.length()>15){
			if(newip.indexOf(",")>0){
				newip = newip.substring(0,newip.indexOf(","));
			}
		}
		user2.setLoginIp(newip);
		baseMapper.updateById(user2);
		sysLogService.addLoginLog(request, username);

	}

	@Override
	public void deleteBatch(Long[] userId) {
		this.deleteBatchIds(Arrays.asList(userId));
	}


	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {


		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setPassword(newPassword);
		return this.update(userEntity,
				new EntityWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
	}
}
